<?php
session_start();
error_reporting(E_ALL);

require 'dbvars.php';

// Connect to server and select databse.
$con = new mysqli("$host", "$username", "$password", "$db_name");
if ($con->connect_error)
{
    die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}

// username and password sent from form 
$name = $_POST['name']; 
$coords = $_POST['submit'];
$descr = $_POST['descr'];
$gobjId = $_SESSION['gobjId']; // Doesn't post for some reason...

// To protect MySQL injection
$name = $con->real_escape_string($name);
$coords = $con->real_escape_string($coords);
$descr = $con->real_escape_string($descr);
$uid = $_SESSION['uid'];
// update gobject data
$sql = "UPDATE $gobject_tbl_name SET name='$name', coords='$coords', description='$descr' WHERE id=$gobjId";
$con->query($sql);

// update references
$stmt = $con->prepare("DELETE FROM $gobjectref_tbl_name WHERE referer = ?");
$stmt->bind_param("i",$gobjId);
$stmt->execute();

$query = "SELECT * FROM $gobject_tbl_name";
$result = $con->query($query);
$rows = $result->num_rows;

$stmt = $con->prepare("INSERT IGNORE INTO $gobjectref_tbl_name (referer, referee) VALUES (?, ?)");
$stmt->bind_param("ii",$thisId,$relatedId);
$thisId = $gobjId;
$thisId = $gobjId;
// for each gobject, check if it is mentioned in this description
for($i = 0; $i< $rows; $i++)
{
	$row = $result->fetch_row();
	$otherName = $row[1];
	$otherId = $row[0];
	
	if($otherId != $gobjId && strstr($descr,$otherName) != FALSE)
	{
		// this description mentions the other object
		// create a reference
		$relatedId = $otherId;
		$stmt->execute();
	}
}

$con->close();

header("location:selected.php?gobjId=$gobjId");

?>
